import numpy as np
from typing import Dict
from datetime import datetime, timedelta

class VolatilityMonitor:
    """波动率实时监控引擎"""
    
    def __init__(self, config: Dict):
        self.window_size = config.get('window_size', 20)  # 波动率计算窗口
        self.threshold = config.get('threshold', 0.15)    # 波动率阈值
        self.price_history = {}  # 各品种价格历史 {symbol: [prices]}
        
    def update_and_check(self, symbol: str, price: float) -> bool:
        """更新价格并检查波动率"""
        if symbol not in self.price_history:
            self.price_history[symbol] = []
            
        prices = self.price_history[symbol]
        prices.append(price)
        
        # 保持窗口大小
        if len(prices) > self.window_size:
            prices.pop(0)
            
        if len(prices) < 2:
            return False
            
        returns = np.diff(prices) / prices[:-1]
        volatility = np.std(returns) * np.sqrt(252)  # 年化波动率
        
        return volatility > self.threshold

class DrawdownController:
    """最大回撤控制器"""
    
    def __init__(self, max_drawdown: float = 0.1):
        self.max_drawdown = max_drawdown
        self.peak = -np.inf
        self.current = 0
        
    def update(self, portfolio_value: float) -> bool:
        """更新组合价值并检查回撤"""
        self.current = portfolio_value
        self.peak = max(self.peak, portfolio_value)
        current_drawdown = (self.peak - self.current) / self.peak
        return current_drawdown > self.max_drawdown

class FrequencyLimiter:
    """交易频率限制器"""
    
    def __init__(self, max_orders: int = 50, period: str = '1H'):
        self.max_orders = max_orders
        self.period = timedelta(**{
            'H': {'hours': 1},
            'D': {'days': 1}
        }[period[-1]])
        self.order_history = []
        
    def check_limit(self) -> bool:
        """检查交易次数是否超限"""
        now = datetime.now()
        # 清除过期记录
        self.order_history = [t for t in self.order_history if now - t < self.period]
        return len(self.order_history) >= self.max_orders
    
    def record_order(self):
        """记录交易时间"""
        self.order_history.append(datetime.now())